import json
from collections import Counter
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, WordCloud

# 英雄类型映射
HERO_TYPE_MAP = {
    1: "战士",
    2: "法师",
    3: "坦克",
    4: "刺客",
    5: "射手",
    6: "辅助"
}

def load_hero_data():
    """加载英雄数据"""
    # 打开并读取JSON文件，返回解析后的Python对象
    with open("herolist.json", "r", encoding="utf-8") as f:
        return json.load(f)

def analyze_hero_types(heroes):
    """分析各类型英雄数量"""
    type_counter = Counter()
    for hero in heroes:
        hero_type = hero.get("hero_type")
        if hero_type:
            type_counter[HERO_TYPE_MAP[hero_type]] += 1
            
        # 处理副职业
        hero_type2 = hero.get("hero_type2")
        if hero_type2:
            type_counter[HERO_TYPE_MAP[hero_type2]] += 1
    
    return type_counter

def analyze_skin_count(heroes):
    """分析每个英雄的皮肤数量"""
    skin_counts = []
    for hero in heroes:
        skins = hero.get("skin_name", "")
        if skins:
            count = len(skins.split("|"))
            skin_counts.append((hero["cname"], count))
        else:
            skin_counts.append((hero["cname"], 0))
    
    # 按皮肤数量排序
    skin_counts.sort(key=lambda x: x[1], reverse=True)
    return skin_counts

def create_hero_type_chart(type_counter):
    """创建英雄类型分布柱状图"""
    types = list(type_counter.keys())
    counts = list(type_counter.values())
    
    bar = (
        Bar()
        .add_xaxis(types)
        .add_yaxis("英雄数量", counts)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="王者荣耀各类型英雄数量"),
            yaxis_opts=opts.AxisOpts(name="英雄数量"),
            xaxis_opts=opts.AxisOpts(name="英雄类型")
        )
    )
    return bar

def create_hero_type_pie_chart(type_counter):
    """创建英雄类型分布饼图"""
    data = list(zip(type_counter.keys(), type_counter.values()))
    
    pie = (
        Pie()
        .add("", data)
        .set_global_opts(title_opts=opts.TitleOpts(title="王者荣耀各类型英雄占比"))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    )
    return pie

def create_skin_count_bar(skin_counts, top_n=20):
    """创建英雄皮肤数量柱状图"""
    # 取前N个皮肤最多的英雄
    top_heroes = skin_counts[:top_n]
    names = [hero[0] for hero in top_heroes]
    counts = [hero[1] for hero in top_heroes]
    
    bar = (
        Bar()
        .add_xaxis(names)
        .add_yaxis("皮肤数量", counts)
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"王者荣耀皮肤数量Top{top_n}英雄"),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45)),
            yaxis_opts=opts.AxisOpts(name="皮肤数量")
        )
    )
    return bar

def create_skin_distribution_wordcloud(skin_counts):
    """创建皮肤数量词云图"""
    wordcloud_data = [(hero[0], count) for hero, count in skin_counts]
    
    wordcloud = (
        WordCloud()
        .add("", wordcloud_data, word_size_range=[20, 100])
        .set_global_opts(title_opts=opts.TitleOpts(title="英雄皮肤数量词云图"))
    )
    return wordcloud

def main():
    # 加载数据
    heroes = load_hero_data()
    
    # 分析各类型英雄数量
    type_counter = analyze_hero_types(heroes)
    
    # 分析皮肤数量
    skin_counts = analyze_skin_count(heroes)
    
    # 创建图表
    hero_type_bar = create_hero_type_chart(type_counter)
    hero_type_bar.render("英雄类型分布柱状图.html")
    
    hero_type_pie = create_hero_type_pie_chart(type_counter)
    hero_type_pie.render("英雄类型分布饼图.html")
    
    skin_count_bar = create_skin_count_bar(skin_counts)
    skin_count_bar.render("英雄皮肤数量柱状图.html")
    
    skin_wordcloud = create_skin_distribution_wordcloud(skin_counts)
    skin_wordcloud.render("英雄皮肤数量词云图.html")
    
    # 输出统计信息到控制台
    print("=== 王者荣耀英雄数据分析 ===")
    print("\n各类型英雄数量:")
    for hero_type, count in type_counter.items():
        print(f"{hero_type}: {count}")
        
    print(f"\n皮肤数量最多的前5名英雄:")
    for i, (name, count) in enumerate(skin_counts[:5]):
        print(f"{i+1}. {name}: {count}款皮肤")
        
    print(f"\n皮肤数量最少的前5名英雄:")
    for i, (name, count) in enumerate(skin_counts[-5:]):
        print(f"{len(skin_counts)-4+i}. {name}: {count}款皮肤")

if __name__ == "__main__":
    main()